<template>
  <div class="energy-data-box">
    <el-form ref="form" :model="formData" :rules="rules" label-width="110px">
      <template v-for="(item, index) in formList">
        <el-form-item
          :key="`${item.prop}${index}`"
          :style="item.itemStyle || {}"
          :label="item.name"
          :prop="item.prop"
          :class="item.itemClass"
        >
          <component
            :is="item.componentType || 'el-input'"
            v-if="item.prop"
            v-model="formData[item.prop]"
            :clearable="true"
            :class="item.class"
            v-bind="item.attrConfig || {}"
            @change="handlerSelectData(item)"
          >
            <template v-if="item.prop === 'solidifyDateRange'" #time-spinner="{item,disableDate}">
              <el-time-picker is-range format="HH" value-format="HH"></el-time-picker>
            </template>
            <template v-for="option in item.optionList">
              <el-option
                :key="option.code"
                :label="option.name"
                :value="option.code"
              />
            </template>
          </component>
        </el-form-item>
      </template>
    </el-form>
  </div>
</template>

<script>
import { dictMixin } from '@/mixin/dict'
import { parseSceneData, parseToSceneInfo } from '@/utils/scene-data'
import roomApi from '@/api/apis/sceneRoom'

export default {
  name: 'AddEnergyData',
  mixins: [dictMixin],
  props: {
    // 请求参数
    requestParams: {
      type: Object,
      default: () => ({})
    },
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isAdd: true,
      formData: {},
      formList: [
        {
          name: '数据时间',
          prop: 'solidifyDateRange',
          attrConfig: {
            valueFormat: 'yyyy-MM-dd HH',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期',
            format: 'yyyy-MM-dd HH',
            type: 'datetimerange',
            popperClass: 'date-picker-pop-format-hour'
          },
          componentType: 'el-date-picker',
          style: { width: '100%' }
        },
        {
          name: '所属项目',
          prop: 'sceneProjectId',
          componentType: 'el-select',
          optionList: [],
          selectPath: 'commonSelected',
          selectParams: {
            code: 'SceneProjectSelected'
          },
          attrConfig: {
            placeholder: '请选择所属项目',
            options: []
          },
          dataProp: {
            dataType: 'resData',
            nameProp: 'label',
            codeProp: 'value'
          },
          selectStyle: { width: '180px' }
        },
        {
          name: '所属场景',
          prop: 'sceneInfo',
          componentType: 'el-cascader',
          attrConfig: {
            placeholder: '请选择所属场景',
            props: {
              checkStrictly: true
            },
            options: []
          }
        },
        // {
        //   name: '所属设备',
        //   prop: 'meterDeviceId',
        //   optionList: [],
        //   componentType: 'el-select',
        //   attrConfig: {
        //     placeholder: '请选择所属设备'
        //   }
        // },
        {
          name: '统计产品类型',
          prop: 'productTypeId',
          componentType: 'el-select',
          optionList: [],
          selectPath: 'commonSelected',
          selectParams: {
            code: 'ProductTypeSelected'
          },
          attrConfig: {
            placeholder: '请选择统计产品类型',
            options: []
          },
          dataProp: {
            dataType: 'resData',
            nameProp: 'label',
            codeProp: 'value'
          },
          style: { width: '100%' }
        }, {
          name: '设备编码',
          prop: 'deviceCode',
          attrConfig: {}
        }, {
          name: '设备名称',
          prop: 'deviceName',
          attrConfig: {}
        },
        {
          prop: 'readMeterType',
          componentType: 'el-select',
          name: '读表类型',
          optionList: [],
          dataProp: {
            keyProp: 'ecp-admin.meterDevice.readMeterType',
            nameProp: 'label',
            codeProp: 'value'
          },
          selectStyle: { width: '180px' },
          selectConfig: {
            clearable: true,
            placeholder: '请选择读表类型'
          }
        }, {
          name: '读表标识',
          prop: 'readMeterTag',
          componentType: 'el-select',
          optionList: [],
          attrConfig: {
            placeholder: '请选择读表标识',
            options: []
          },
          dataProp: {
            keyProp: 'ecp-admin.meterDevice.readMeterTag',
            nameProp: 'label',
            codeProp: 'value'
          },
          selectStyle: { width: '100%' }
        }, {
          name: '统计类型',
          prop: 'staticsType',
          componentType: 'el-select',
          optionList: [],
          selectPath: 'commonSelected',
          selectParams: {
            code: 'MeterDeviceStaticsType'
          },
          attrConfig: {
            placeholder: '请选择统计类型',
            options: []
          },
          dataProp: {
            dataType: 'resData',
            nameProp: 'label',
            codeProp: 'value'
          },
          selectStyle: { width: '100%' }
        },
        {
          name: '能源名称',
          prop: 'energyTypeId',
          componentType: 'el-select',
          optionList: [],
          selectPath: 'commonSelected',
          selectParams: {
            code: 'EnergyConsumptionTypeSelected'
          },
          attrConfig: {
            placeholder: '请选择能源名称',
            style: { width: '100%' },
            options: []
          },
          dataProp: {
            dataType: 'resData',
            nameProp: 'label',
            codeProp: 'value'
          }
        }, {
          name: '能源分类',
          prop: 'energyCategory',
          componentType: 'el-select',
          optionList: [],
          selectPath: 'commonSelected',
          selectParams: {
            code: 'EnergyCategorySelected'
          },
          attrConfig: {
            placeholder: '请选择能源分类',
            options: []
          },
          dataProp: {
            dataType: 'resData',
            nameProp: 'label',
            codeProp: 'value'
          },
          selectStyle: { width: '180px' }
        },
        {
          name: '单位',
          prop: 'energyTypeUnit',
          attrConfig: {},
          selectStyle: { width: '100%' }
        }, {
          name: '测算范围',
          prop: 'calculationRange',
          componentType: 'el-select',
          optionList: [],
          selectPath: 'commonSelected',
          selectParams: {
            code: 'CarbonEmissionRangeSelected'
          },
          attrConfig: {
            placeholder: '请选择测算范围',
            options: []
          },
          dataProp: {
            dataType: 'resData',
            nameProp: 'label',
            codeProp: 'value'
          },
          selectStyle: { width: '180px' }
        }, {
          name: '计量值',
          prop: 'meterValue',
          attrConfig: {
            disabled: false,
            type: 'number'
          },
          selectStyle: { width: '100%' }
        },
        /*{
          name: '读数值',
          prop: 'readValue',
          attrConfig: {
            placeholder: '请输入读数值',
            type: 'number'
          }
        },*/ {
          name: '标准煤',
          prop: 'standardCoal',
          attrConfig: {
            placeholder: '请输入标准煤',
            disabled: true,
            type: 'number'
          }
        }
      ]
    }
  },
  computed: {
    rules() {
      return {
        solidifyDateRange: [{ required: true, message: '请选择数据时间', trigger: 'change' }],
        sceneProjectId: [{ required: true, message: '请选择所属项目', trigger: 'change' }],
        sceneInfo: [{ required: false, message: '请选择所属场景', trigger: 'change' }],
        productTypeId: [{ required: true, message: '请选择统计产品类型', trigger: 'change' }],
        deviceCode: [{ required: true, message: '请输入设备编码', trigger: 'change' }],
        deviceName: [{ required: true, message: '请输入设备名称', trigger: 'change' }],
        readMeterType: [{ required: true, message: '请选择读表类型', trigger: 'change' }],
        readMeterTag: [{ required: true, message: '请选择读表标识', trigger: 'change' }],
        staticsType: [{ required: false, message: '请选择统计类型', trigger: 'change' }],
        energyTypeId: [{ required: true, message: '请选择能源名称', trigger: 'change' }],
        energyCategory: [{ required: true, message: '请选择能源分类', trigger: 'change' }],
        energyTypeUnit: [{ required: true, message: '请输入单位', trigger: 'change' }],
        calculationRange: [{ required: true, message: '请输入测算范围', trigger: 'change' }],
        meterValue: [{ required: true, message: '请输入计量值', trigger: 'change' }],
        readValue: [{ required: true, message: '请输入读数值', trigger: 'change' }],
        standardCoal: [{ required: false, message: '请输入标准煤', trigger: 'change' }]
      }
    }
  },
  watch: {
    popData: {
      handler(data) {
        const { popType } = this.popConfig
        const dataId = ['add'].includes(popType) ? '' : data.id
        this.isAdd = !dataId
        if (!this.isAdd) {
          this.formList = this.formList.filter(item => item.prop !== 'solidifyDateRange')
        }
        this.formList.forEach((e) => {
          this.$set(this.formData, e.prop, data[e.prop])
          if (!this.isAdd && ['solidifyDate', 'sceneProjectId', 'sceneInfo', 'productTypeId',
            'deviceCode', 'deviceName', 'readMeterType', 'readMeterTag', 'staticsType',
            'energyTypeId', 'energyCategory', 'energyTypeUnit', 'calculationRange', 'readValue', 'standardCoal'].includes(e.prop)) {
            if (e.attrConfig == null) {
              e.attrConfig = {}
            }
            e.attrConfig.disabled = true
          }
        })
        this.$set(this.formData, 'energyTypeId', data.energyTypeId)
        this.$set(this.formData, 'solidifyDate', data.solidifyDate)
        this.$set(this.formData, 'id', dataId)
        this.queryMeterDeviceByProjectId(data.sceneProjectId || '')
        this.formData.sceneInfo = parseToSceneInfo(data)
        if (data.sceneProjectId) {
          // 查询场景选择的数据
          this.getRoomList(data.sceneProjectId)
        }
        // this.formList[2].optionList = [{ code: this.formData.productTypeId, name: data.productTypeName }]
      },
      deep: true,
      immediate: true
    },
    confirm() {
      const params = {
        ...(this.formData || {})
      }
      this.submit(params)
    }
  },
  created() {
    /** 获取字典数据 */
    this.getDictData()
  },
  methods: {
    async getRoomList(sceneProjectId) {
      const res = await roomApi.queryRoomList({
        sceneProjectId,
        sortColumn: 'floorName',
        sortOrder: 'asc'
      })
      const roomList = parseSceneData(res.data)
      const index = this.formList.findIndex(item => item.prop === 'sceneInfo')
      const item = this.formList[index]
      item.attrConfig.options = roomList
      this.$set(this.formList, index, { ...item })
    },
    setPropFromDeviceInfo() {
      this.$api.meterDevice.detailByCode(this.formData.deviceCode).then(async res => {
        if (res.data != null) {
          this.formData.sceneProjectId = res.data.sceneProjectId
          this.formData.deviceName = res.data.deviceName
          this.formData.productTypeId = res.data.productTypeId
          this.formData.readMeterType = res.data.readMeterType
          this.formData.readMeterTag = res.data.readMeterTag
          this.formData.staticsType = res.data.staticsType
          this.formData.energyTypeId = res.data.energyTypeId
          this.formData.energyTypeUnit = res.data.energyTypeUnit
          this.formData.energyCategory = res.data.energyCategory
          this.formData.calculationRange = res.data.calculationRange
          await this.getRoomList(this.formData.sceneProjectId)
          const sceneInfo = []
          if (res.data.sceneEdificeId != null) {
            sceneInfo.push(res.data.sceneEdificeId)
          }
          if (res.data.sceneFloorId != null) {
            sceneInfo.push(res.data.sceneFloorId)
          }
          if (res.data.sceneRoomId != null) {
            sceneInfo.push(res.data.sceneRoomId)
          }
          this.formData.sceneInfo = sceneInfo

        }
      })
    },
    /**
     * change事件
     */
    handlerSelectData(config) {
      const Ref = this.$refs[config.prop]
      if (Ref && config.isClosePop) {
        Ref.dropDownVisible = false
      }
      if (config.prop === 'deviceCode') {
        this.setPropFromDeviceInfo()
      }
      if (config.prop === 'sceneProjectId') {
        this.$set(this.formData, 'meterDeviceId', '')
        this.$set(this.formData, 'readMeterTag', '')
        this.$set(this.formData, 'readMeterType', '')
        this.$set(this.formData, 'energyType', '')
        this.$set(this.formData, 'energyTypeUnit', '')
        this.$set(this.formData, 'energyTypeId', '')
        this.queryMeterDeviceByProjectId(this.formData[config.prop])
        this.getRoomList(this.formData.sceneProjectId)
      }
      if (config.prop === 'meterDeviceId') {
        const meterObj = config.optionList.find(t => t.value === this.formData.meterDeviceId).baseObj
        if (meterObj !== null) {
          this.$set(this.formData, 'readMeterTag', meterObj.readMeterTag)
          this.$set(this.formData, 'readMeterType', meterObj.readMeterType)
          this.$set(this.formData, 'energyType', meterObj.energyType)
          this.$set(this.formData, 'energyTypeUnit', meterObj.energyTypeUnit)
          this.$set(this.formData, 'energyTypeId', meterObj.energyTypeId)
          this.querySceneInfo(meterObj.sceneEdificeId, meterObj.sceneFloorId, meterObj.sceneRoomId)
        }
      } else if (config.prop === 'sceneInfo') {
        if (this.formData.sceneInfo != null && this.formData.sceneInfo.length > 0) {
          this.formData.sceneEdificeId = this.formData.sceneInfo[0]
          this.formData.sceneFloorId = this.formData.sceneInfo.length > 1 ? this.formData.sceneInfo[1] : null
          this.formData.sceneRoomId = this.formData.sceneInfo.length > 2 ? this.formData.sceneInfo[2] : null
        } else {
          this.formData.sceneEdificeId = null
          this.formData.sceneFloorId = null
          this.formData.sceneRoomId = null
        }
      }
    },
    async getDictData() {
      const res = await this.$api.dictList({
        codeList: [
          'ecp-admin.meterDevice.readMeterTag',
          'ecp-admin.meterDevice.readMeterType'
        ]
      })
      for (let i = 0; i < this.formList.length; i++) {
        const item = this.formList[i]
        const { keyProp } = item.dataProp || {}
        if (keyProp) {
          item.optionList = res.data[keyProp].map(dict => {
            dict.name = dict.label
            dict.code = dict.value
            return dict
          })
          if (i === 6 && this.formData.meterType) {
            this.handlerSelectMeterType(this.formData.meterType, false)
          }
          this.$set(this.formList, i, { ...item })
        }
      }
    },
    /**
     * 提交
     */
    submit(params) {
      if (params.solidifyDateRange != null && params.solidifyDateRange.length > 1) {
        params.solidifyDateStart = params.solidifyDateRange[0]
        params.solidifyDateEnd = params.solidifyDateRange[1]
      }
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const res = await this.$api.energyData[
            this.isAdd ? 'add' : 'update'
            ](params)
          if (Number(res.code) === 1000) {
            this.$message.success(`${this.isAdd ? '新增' : '编辑'}成功！`)
            this.$emit('onFinish', 'energy-data-add')
          }
        }
      })
    },
    /**
     * 通过项目Id查询计量设备
     * @param sceneProjectId
     * @returns {Promise<void>}
     */
    async queryMeterDeviceByProjectId(sceneProjectId) {
      const res = await this.getCommonSelecteds('MeterDeviceSelected', '', `{'sceneProjectId':'${sceneProjectId}'}`)
      const idx = this.formList.findIndex((e => e.prop === 'meterDeviceId'))
      const item = this.formList.find((e => e.prop === 'meterDeviceId'))
      const optionList = res.map(e => {
        return {
          ...e,
          code: e.value,
          name: e.label
        }
      }) || []
      this.$set(this.formList, idx, {
        ...item,
        optionList
      })
    },
    /**
     * 通过楼栋Id / 楼层Id / 空间Id 获取所属场景
     * @param sceneEdificeId
     * @param sceneFloorId
     * @param sceneRoomId
     * @returns {Promise<void>}
     */
    async querySceneInfo(sceneEdificeId, sceneFloorId, sceneRoomId) {
      const sceneInfo = await this.$api.energyData.querySceneInfo({
        sceneEdificeId,
        sceneFloorId,
        'id': sceneRoomId
      })
      this.$set(this.formData, 'sceneInfo', sceneInfo.data)
      console.log(this.formData)
    }
  }
}
</script>

<style lang="scss" scoped>
.energy-data-box {
  color: #333;
  padding: 0 20px;

  ::v-deep .el-form {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    .el-form-item {
      width: calc(50% - 10px);

      &.width100p {
        width: 100%;
      }

      .el-form-item__label {
        color: #666;
        font-size: 14px;
      }

      &.form-sub-title {
        width: 100%;

        .el-form-item__label {
          display: flex;
          align-items: center;
          justify-content: flex-start;
          font-weight: bold;
          color: #333;
          font-size: 16px;
          line-height: 1;

          &::before {
            content: '';
            display: inline-block;
            width: 4px;
            height: 15px;
            background-color: #00858d;
            margin-right: 5px;
          }
        }
      }
    }

    .el-select,
    .el-cascader {
      width: 100%;
    }
  }
}

</style>
